//
//  SuspendView.m
//  ICrEAM
//
//  Created by mac on 16/11/1.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "SuspendView.h"
#import "Masonry.h"
#import "AppDelegate.h"
NSString *const SuspendViewClickNotification = @"SuspendViewClickNotification";
@interface SuspendView()<SubMenuDelegate,SubMenuDataSource>
@property(nonatomic,strong)NSArray* subMenus;
@property(nonatomic,assign)NSInteger selectIndex;
@property(nonatomic,strong)UIView *coverView;
@end
@implementation SuspendView
-(UIView *)coverView{
    if(!_coverView){
        
        _coverView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth-35, ScreenHeight)];
        
    }
    return _coverView;
}
-(SubMenu *)menu{
    if (!_menu) {
        _menu=[[SubMenu alloc]initWithDirection:DirectionLeftType];
        _menu.delegate=self;
        _menu.datasource=self;
        
    }
    return _menu;
}
- (void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
-(instancetype)initWithFrame:(CGRect)frame{
    self=[super initWithFrame:frame];
    if (self) {
        //        self.backgroundColor=[UIColor redColor];

        _buttonArray=[NSMutableArray array];
        if ([ICrEAMUser shareICrEAMUser].userType==ConsultantType) {
            self.subMenus=@[@[@"维修进度看板"],@[@"创建预约单",@"预约查询"],@[],@[@"创建接车单",@"接车单查询"],@[],@[],@[],@[] ];
        }else if([ICrEAMUser shareICrEAMUser].userType==WorkshopType){
            self.subMenus=@[@[@"车间进度看板"]];
        }
        
        else{
            self.subMenus=@[@[@"维修进度看板",@"车间进度看板"],@[@"创建预约单",@"预约查询"],@[],@[@"创建接车单",@"接车单查询"],@[],@[],@[],@[] ];
        }
        if ([ICrEAMTool isVW]) {
            self.btns=@[@{@"title":@"监控",@"image":@"monitor_image",@"heightimage":@"monitor_height_image"},@{@"title":@"预约",@"image":@"appoint_image",@"heightimage":@"appoint_height_image"},@{@"title":@"准备",@"image":@"ready_image",@"heightimage":@"ready_height_image"},@{@"title":@"接车",@"image":@"getcar_image",@"heightimage":@"getcat_height_image"},@{@"title":@"委托书",@"image":@"proxy_image",@"heightimage":@"proxy_height_image"},@{@"title":@"终检",@"image":@"endcheck_image",@"heightimage":@"endcheck_height_image"},@{@"title":@"结算",@"image":@"balance_image",@"heightimage":@"balance_height_image"},@{@"title":@"查阅",@"image":@"search_document_image",@"heightimage":@"search_height_image"}];
        }else{
        self.btns=@[@{@"title":@"监控",@"image":@"monitor_image",@"heightimage":@"monitor_height_image_sk"},@{@"title":@"预约",@"image":@"appoint_image",@"heightimage":@"appoint_height_image_sk"},@{@"title":@"准备",@"image":@"ready_image",@"heightimage":@"ready_height_image_sk"},@{@"title":@"接车",@"image":@"getcar_image",@"heightimage":@"getcat_height_image_sk"},@{@"title":@"委托书",@"image":@"proxy_image",@"heightimage":@"proxy_height_image_sk"},@{@"title":@"终检",@"image":@"endcheck_image",@"heightimage":@"endcheck_height_image_sk"},@{@"title":@"结算",@"image":@"balance_image",@"heightimage":@"balance_height_image_sk"},@{@"title":@"查阅",@"image":@"search_document_image",@"heightimage":@"search_height_image_sk"}];
        }
            _boardView = [[TopMenuView alloc] initWithFrame:CGRectMake(0, 0, frame.size.width, frame.size.height)];
        [self addSubview:_boardView];
        _boardView.backgroundColor = [UIColor darkGrayColor];
        _boardView.selfBoard = self;
        _boardView.backgroundImageView.image=[UIImage imageNamed:@"menu"];
        _boardView.autoresizingMask = UIViewAutoresizingNone;
        
        UITapGestureRecognizer *gesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesHundel:)];
        [_boardView addGestureRecognizer:gesture];
        
    }
    return self;
}
#pragma mark- gesture
- (void)tapGesHundel:(UITapGestureRecognizer *)gesture{
    if (_animating) {
        return;
    }
    if (!_isOpen) {
        [self boardOpen];
        if ([self.delegate respondsToSelector:@selector(openBoard)]) {
            [self.delegate openBoard];
        }
        
    }else{
        [self boardClose];
        if ([self.delegate respondsToSelector:@selector(closeBoard)]) {
            [self.delegate closeBoard];
        }
    }
}
- (void)startRunning
{
    
  
    self.hidden = NO;
    
}

- (void)stopRunning
{
    
    self.hidden = YES;
}

#pragma mark- button
- (void)buttonAction:(UIButton *)sender
{
    for (UIButton *btn  in _buttonArray) {
        btn.selected=NO;
    }
    sender.selected=YES;
    self.selectIndex=sender.tag-100;
    NSArray *sub=self.subMenus[self.selectIndex];
    if (sub.count>0) {
        [self.menu showDownFrom:sender withx:-100 andWith:140];
    }else{
        [self.menu dismiss];
//        MainViewController *main=[AppDelegate mainViewController];
//        if (main.navigationController.viewControllers.count>1) {
//            [main.navigationController popToRootViewControllerAnimated:NO];
//        }
 
        [self boardClose];
        [[NSNotificationCenter defaultCenter]postNotificationName:SuspendViewClickNotification object:nil userInfo:@{@"ctrType":[NSString stringWithFormat:@"%d",sender.tag-100]}];
    }
    //    [self.controller.navigationController popToRootViewControllerAnimated:NO];
    //    [[NSNotificationCenter defaultCenter]postNotificationName:SuspendViewClickNotification object:sender userInfo:nil];
}
-(void)SubMenuControllerDidClickIndex:(NSInteger)index{
    NSInteger ctrType=self.selectIndex*2+index+8;
    MainViewController *main=[AppDelegate currentAppDelegate].main;
    if (main.navigationController.viewControllers.count>1) {
        [main.navigationController popToRootViewControllerAnimated:NO];
    }
    //      [self.controller.navigationController popToRootViewControllerAnimated:NO];
    [self boardClose];
    [[NSNotificationCenter defaultCenter]postNotificationName:SuspendViewClickNotification object:nil userInfo:@{@"ctrType":[NSString stringWithFormat:@"%d",ctrType]}];
}
-(NSInteger)numberOfRowsInSubMenu{
    NSArray *sub=self.subMenus[self.selectIndex];
    return sub.count;
}
-(NSString *)titileForSubMenuInRow:(NSInteger)row{
    NSArray *sub=self.subMenus[self.selectIndex];
    return sub[row];
}
#pragma mark- method
- (void)boardOpen
{

    _animating = YES;
    _boardRect = self.frame;
    
    _boardView.backgroundImageView.image=[UIImage imageNamed:@"icon_Menuclose"];
    
    for (int i = 0; i < _buttonNumber; i++)
    {
        MenuIcon *button = [[MenuIcon alloc] initWithFrame:CGRectMake(0, 0, 75, 65)];
        
        
        button.adjustsImageWhenHighlighted = NO;
        button.backgroundColor=[UIColor blackColor];
        NSDictionary *dic=self.btns[i];
        button.titleLabel.font=[UIFont systemFontOfSize:14];
        [button setTitle:dic[@"title"] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:dic[@"image"]] forState:UIControlStateNormal];
        [button setImage:[UIImage imageNamed:dic[@"heightimage"]] forState:UIControlStateSelected];
        [button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];;
        if ([ICrEAMTool isVW]) {
              [button setTitleColor:RGB(35, 193, 239) forState:UIControlStateSelected];;
        }else{
              [button setTitleColor:KSKBgColor forState:UIControlStateSelected];;
       
        }
      
        [self addSubview:button];
        
        [_buttonArray addObject:button];
        button.tag = i+100;
        [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
        
    }
    
    
    int direction = [_boardView directByPoint:_boardView.center];
    CGFloat height=30;
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = CGRectMake(ScreenWidth-65, _boardRect.origin.y, 65, 65+_buttonNumber*75);
                         _boardView.frame = CGRectMake(0, 0, 65, 35);
                         
                         for (int i = 0; i<_buttonArray.count; i++)
                         {
                             UIButton *button = [_buttonArray objectAtIndex:i];
                             
                             switch (direction)
                             {
                                 case 0://modify  by  maxingxing
                                     button.frame = CGRectMake(0,height+i*75, 65, 75);
                                     break;
                                 case 1:
                                     button.frame = CGRectMake(0,height+i*75, 65, 75);
                                     
                                     break;
                                 case 2:
                                     button.frame = CGRectMake(0,height+i*75, 65, 75);
                                     break;
                                 case 3:
                                     button.frame = CGRectMake(0,height+i*75, 65, 75);
                                     break;
                                     
                                 default:
                                     break;
                             }
                         }
                     }
                     completion:^(BOOL finished)
     {
         
         _animating = NO;
         _isOpen = YES;
         //         UITapGestureRecognizer *windowTapGes = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(windowTaped:)];
         //         [_boardWindow addGestureRecognizer:windowTapGes];
         
     }];
    
}


- (void)boardClose{
    [self.menu dismiss];
    _animating = YES;
    [UIView animateWithDuration:0.3
                     animations:^{
                         self.frame = _boardRect;
                         for (int i = 0; i<_buttonArray.count; i++)
                         {
                             MenuIcon *button = [_buttonArray objectAtIndex:i];
                             button.frame = _boardRect;
                         }
                     }
                     completion:^(BOOL finished)
     {
         for (int i = 0; i<_buttonArray.count; i++){
             UIButton *button = [_buttonArray objectAtIndex:i];
             [button removeFromSuperview];
         }
         [_buttonArray removeAllObjects];
         
         _animating = NO;
         _isOpen = NO;
         self.frame = _boardRect;
         _boardView.frame=CGRectMake(0, 0, _boardRect.size.width, _boardRect.size.height);
         _boardView.backgroundImageView.image=[UIImage imageNamed:@"menu"];
         
         //         _boardView.frame = CGRectMake(0, 0, _boardSize, _boardSize);
         [self removeGestureRecognizer:[[self gestureRecognizers] lastObject]];
     }];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self boardClose];
}
@end

@implementation TopMenuView

- (id)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        _backgroundImageView = [[UIImageView alloc] init];
        _backgroundImageView.userInteractionEnabled=YES;
        _backgroundImageView.translatesAutoresizingMaskIntoConstraints=NO;
        [self addSubview:_backgroundImageView];
        [_backgroundImageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.leading.equalTo(self.mas_leading).with.offset(0);
            make.trailing.equalTo(self.mas_trailing).with.offset(0);
            make.top.equalTo(self.mas_top).with.offset(0);
            make.bottom.equalTo(self.mas_bottom).with.offset(0);
            
        }];
        
    }
    
    return self;
}


- (void)dealloc{
    self.backgroundImageView = nil;
    
}

- (void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    if (_selfBoard.animating)
    {
        return;
    }
    
    UITouch *touch = [touches anyObject];
    _beginPoint = [touch locationInView:self.window];
    _selfBeginCenter = self.center;
}


- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    if (_moving) {
        _moving = NO;
        UITapGestureRecognizer *ges = [self.gestureRecognizers lastObject];
        ges.enabled = YES;
        UITouch *touch = [touches anyObject];
        CGPoint point = [touch locationInView:self.window];
        self.window.center = CGPointMake(self.window.center.x + (point.x - _beginPoint.x),
                                         self.window.center.y + (point.y - _beginPoint.y));
        
        self.frame = CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
        
        if (self.selfBoard.autoPosition) {
            NSInteger direction = INT16_MAX;
            
            
            if (_direction != NSNotFound) {
                direction = _direction;
            }else{
                direction = [self directByPoint:self.window.center];
            }
            
            CGRect newRect;
            
            switch (direction) {
                case 0:
                    newRect = CGRectMake(self.window.frame.origin.x,
                                         0,
                                         self.window.frame.size.width,
                                         self.window.frame.size.height);
                    break;
                case 1:
                    newRect = CGRectMake([[UIScreen mainScreen] bounds].size.width - self.window.frame.size.width,
                                         self.window.frame.origin.y,
                                         self.window.frame.size.width,
                                         self.window.frame.size.height);
                    break;
                case 2:
                    newRect = CGRectMake(self.window.frame.origin.x,
                                         [[UIScreen mainScreen] bounds].size.height - self.window.frame.size.height,
                                         self.window.frame.size.width,
                                         self.window.frame.size.height);
                    break;
                case 3:
                    newRect = CGRectMake(0,
                                         self.window.frame.origin.y,
                                         self.window.frame.size.width,
                                         self.window.frame.size.height);
                    break;
                    
                default:
                    break;
            }
            
            [UIView animateWithDuration:0.3
                             animations:^{
                                 self.window.frame = newRect;
                             }
                             completion:^(BOOL finished) {
                                 
                             }];
            self.selfBoard.movedWithKeyboard = NO;
        }
    }
}

- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event{
    if (_moving) {
        _moving = NO;
        UITapGestureRecognizer *ges = [self.gestureRecognizers lastObject];
        ges.enabled = YES;
        UITouch *touch = [touches anyObject];
        CGPoint point = [touch locationInView:self.window];
        self.window.center = CGPointMake(self.window.center.x + (point.x - _beginPoint.x),
                                         self.window.center.y + (point.y - _beginPoint.y));
        self.frame = CGRectMake(0, 0, self.window.frame.size.width, self.window.frame.size.height);
    }
}

#pragma mark- tool

- (int)directByPoint:(CGPoint)point{
    int dir = INT_MAX;
    int min = INT_MAX;
    if (fabs(point.x - 0)<min) {
        min = fabs(point.x - 0);
        dir = 3;
    }
    if (fabs([[UIScreen mainScreen] bounds].size.width - point.x)<min) {
        min = fabs([[UIScreen mainScreen] bounds].size.width - point.x);
        dir = 1;
    }
    if (fabs(point.y - 0)<min) {
        min = fabs(point.y - 0);
        dir = 0;
    }
    if (fabs([[UIScreen mainScreen] bounds].size.height - point.y)<min) {
        min = fabs([[UIScreen mainScreen] bounds].size.width - point.x);
        dir = 2;
    }
    
    return dir;
}

- (int)velocityByPoint:(CGPoint)point1 andPoint:(CGPoint)point2
{
    int velocityX = point1.x - point2.x;
    int velocityY = point1.y - point2.y;
    
    if (abs(velocityX) > abs(velocityY))
    {
        return velocityX;
    }
    else
    {
        return velocityY;
    }
}

- (void)layoutSubviews
{
    
    [super layoutSubviews];
}


@end
